package com.chw.common.realms;

import com.chw.dao.IUserDao;

import com.chw.model.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;

public class MyRealm extends AuthorizingRealm {
    @Resource
    private IUserDao userMapping;
    @Autowired
    private HttpServletRequest request;
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
      //得到认证信息
        String userName= (String) authenticationToken.getPrincipal();
        //调用dao层方法
        User user=userMapping.getName(userName);
        if (user==null){
            return null;

        }
        //构建正确的认证信息
        SimpleAuthenticationInfo simpleAuthorizationInfo=new SimpleAuthenticationInfo(userName,user.getPassword(),getName());
        SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
        request.getSession().setAttribute("login_user",user);
        request.getSession().setAttribute("login_user_birthday",sim.format(user.getBirthday()));
        return simpleAuthorizationInfo;
    }
}
